package com.wonders.common.web.captcha.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Producer;
import com.wonders.common.constant.TipConstant;
import com.wonders.common.web.captcha.util.CaptchaUtil;
import com.wonders.framework.config.annotation.NotLogon;
import com.wonders.framework.exception.FrameworkException;
import com.wonders.framework.util.web.RequestUtil;
import com.wonders.framework.web.BaseController;

/**
 * 验证码控制器
 * 
 * @author WuBin
 * 
 */
@NotLogon
@Component
@RequestMapping("/captcha")
public class CaptchaController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(CaptchaController.class);

	/**
	 * 验证码变量前缀
	 */
	public final static String PREFIX = "captcha_";

	@Autowired
	private Producer kaptchaProducer;

	/**
	 * 生成验证码
	 * 
	 * @return
	 */
	@RequestMapping("generate")
	@ResponseBody
	public Object generate() {
		String key = (String) RequestUtil.getRequestParam("key");
		if (StringUtils.isEmpty(key)) {
			return super.ajaxError(TipConstant.PARAM.MISSING);
		}
		RequestUtil.getResponse().setDateHeader("Expires", 0);
		RequestUtil.getResponse().setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");
		RequestUtil.getResponse().addHeader("Cache-Control",
				"post-check=0, pre-check=0");
		RequestUtil.getResponse().setHeader("Pragma", "no-cache");
		RequestUtil.getResponse().setContentType("image/jpeg");
		String captcha = kaptchaProducer.createText();
		RequestUtil.setSessionAttr(StringUtils.join(PREFIX, key), captcha);
		BufferedImage bi = kaptchaProducer.createImage(captcha);
		ServletOutputStream out = null;
		try {
			out = RequestUtil.getResponse().getOutputStream();
			ImageIO.write(bi, "jpg", out);
		} catch (IOException e) {
			RequestUtil.setSessionAttr(StringUtils.join(PREFIX, key), null);
			throw new FrameworkException("生成验证码失败", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					logger.error("关闭流失败", e);
				}
			}
		}
		return null;
	}

	/**
	 * 校验验证码
	 * 
	 * @return
	 */
	@RequestMapping("validate")
	@ResponseBody
	public Object validate() {
		String key = (String) RequestUtil.getRequestParam("key");
		String code = (String) RequestUtil.getRequestParam("code");
		if (StringUtils.isEmpty(key) || StringUtils.isEmpty(code)) {
			return super.ajaxError(TipConstant.PARAM.MISSING);
		}
		if (!CaptchaUtil.validate(key, code)) {
			return super.ajaxError("验证码不正确");
		}
		return super.ajaxSuccess();
	}

}
